<!--
 * 后台管理欢迎页
-->
<template>
  <div class="dashboard">
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-item">
            <div class="stat-value">{{ statsData.totalOrders }}</div>
            <div class="stat-label">总订单数</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-item">
            <div class="stat-value">{{ statsData.totalRevenue }}</div>
            <div class="stat-label">总营业额</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-item">
            <div class="stat-value">{{ statsData.totalFoods }}</div>
            <div class="stat-label">菜品总数</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-item">
            <div class="stat-value">{{ statsData.todayOrders }}</div>
            <div class="stat-label">今日订单</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="24">
        <el-card class="chart-card">
          <div slot="header" class="chart-header">
            <span class="chart-title">食品销量统计</span>
            <div class="chart-controls">
              <el-button-group>
                <el-button size="small" @click="changeTimeRange('week')" :type="timeRange === 'week' ? 'primary' : ''">本周</el-button>
                <el-button size="small" @click="changeTimeRange('month')" :type="timeRange === 'month' ? 'primary' : ''">本月</el-button>
                <el-button size="small" @click="changeTimeRange('year')" :type="timeRange === 'year' ? 'primary' : ''">本年</el-button>
              </el-button-group>
              <el-button size="small" icon="el-icon-refresh" @click="refreshData" :loading="loading" style="margin-left: 10px;">刷新</el-button>
            </div>
          </div>
          <div id="salesChart" class="chart" v-loading="loading" element-loading-text="加载中..."></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  name: 'Home',
  data () {
    return {
      chart: null,
      timeRange: 'month',
      loading: false,
      // 统计数据
      statsData: {
        totalOrders: 0,
        totalRevenue: '¥0',
        totalFoods: 0,
        todayOrders: 0
      },
      // 图表数据
      chartData: {
        categories: [],
        sales: []
      },
      // 默认食品销量数据（当API调用失败时使用）
      defaultSalesData: {
        week: {
          categories: ['宫保鸡丁', '麻婆豆腐', '红烧肉', '糖醋排骨', '鱼香肉丝', '回锅肉', '青椒肉丝'],
          sales: [120, 98, 156, 89, 134, 78, 145]
        },
        month: {
          categories: ['宫保鸡丁', '麻婆豆腐', '红烧肉', '糖醋排骨', '鱼香肉丝', '回锅肉', '青椒肉丝', '水煮鱼', '口水鸡', '蒜蓉西兰花'],
          sales: [456, 389, 612, 345, 523, 298, 567, 234, 445, 189]
        },
        year: {
          categories: ['宫保鸡丁', '麻婆豆腐', '红烧肉', '糖醋排骨', '鱼香肉丝', '回锅肉', '青椒肉丝', '水煮鱼', '口水鸡', '蒜蓉西兰花'],
          sales: [5456, 4389, 6012, 3845, 5123, 2998, 5567, 2834, 4445, 1889]
        }
      }
    }
  },
  async mounted () {
    this.initChart()
    await this.loadDashboardData()
    this.updateChart()
  },
  methods: {
    /**
     * 初始化图表
     */
    initChart () {
      this.chart = echarts.init(document.getElementById('salesChart'))

      // 监听窗口大小变化
      window.addEventListener('resize', this.handleResize)
    },

    /**
     * 处理窗口大小变化
     */
    handleResize () {
      if (this.chart) {
        this.chart.resize()
      }
    },

    /**
     * 加载仪表板数据
     */
    async loadDashboardData () {
      this.loading = true
      try {
        // 并行加载统计数据和销量数据
        await Promise.all([
          this.loadStatsData(),
          this.loadSalesData(this.timeRange)
        ])
      } catch (error) {
        this.$message.error('数据加载失败，显示默认数据')
        this.loadDefaultData()
      } finally {
        this.loading = false
      }
    },

    /**
      * 加载统计数据
      */
    async loadStatsData () {
      try {
        // 并行获取各种统计数据
        const [orderStats, foodStats, revenueStats] = await Promise.all([
          this.getOrderStatistics(),
          this.getFoodStatistics(),
          this.getRevenueStatistics()
        ])

        this.statsData = {
          totalOrders: orderStats.totalOrders || 0,
          totalRevenue: `¥${revenueStats.totalRevenue || 0}`,
          totalFoods: foodStats.totalFoods || 0,
          todayOrders: orderStats.todayOrders || 0
        }
      } catch (error) {
        console.error('加载统计数据失败:', error)
        // 使用默认数据
        this.statsData = {
          totalOrders: 1256,
          totalRevenue: '¥45,680',
          totalFoods: 89,
          todayOrders: 23
        }
      }
    },

    /**
       * 加载食品销量数据
       */
    async loadSalesData (timeRange) {
      try {
        // 根据时间范围获取不同类别的食品数据
        const salesData = await this.fetchFoodSalesData(timeRange)

        if (salesData && salesData.length > 0) {
          // 按销量排序并取前10名
          const sortedFoods = salesData
            .filter(food => food.sales > 0)
            .sort((a, b) => b.sales - a.sales)
            .slice(0, 10)

          this.chartData = {
            categories: sortedFoods.map(food => food.dishesName || food.name),
            sales: sortedFoods.map(food => food.sales || 0)
          }
        } else {
          throw new Error('食品销量数据获取失败')
        }
      } catch (error) {
        console.error('加载食品销量数据失败:', error)
        this.loadDefaultData()
      }
    },

    /**
     * 解析中文日期格式
     */
    parseChineseDate (dateStr) {
      if (!dateStr) return null
      
      try {
        // 处理中文日期格式："2025年06月11日 00:28:06"
        const match = dateStr.match(/(\d{4})年(\d{1,2})月(\d{1,2})日\s+(\d{1,2}):(\d{1,2}):(\d{1,2})/)
        if (match) {
          const [, year, month, day, hour, minute, second] = match
          return new Date(parseInt(year), parseInt(month) - 1, parseInt(day), parseInt(hour), parseInt(minute), parseInt(second))
        }
        
        // 如果不是中文格式，尝试标准解析
        const standardDate = new Date(dateStr)
        return isNaN(standardDate.getTime()) ? null : standardDate
      } catch (error) {
        console.warn('日期解析失败:', dateStr, error)
        return null
      }
    },

    /**
       * 获取订单统计数据 - 通过订单管理的订单进行汇总
       */
    async getOrderStatistics () {
      try {
        console.log('开始获取订单统计数据...')
        // 使用订单管理页面相同的分页接口获取所有订单数据
        let allOrders = []
        let currentPage = 1
        const pageSize = 100 // 使用较大的页面大小减少请求次数
        let hasMoreData = true

        while (hasMoreData) {
          try {
            const response = await this.$http.get(`/orderDetails/current/${currentPage}/size/${pageSize}`)
            if (response && response.code === 200 && response.data && response.data.list) {
              const orders = response.data.list
              console.log(`第${currentPage}页获取到${orders.length}个订单`)
              allOrders = allOrders.concat(orders)

              // 检查是否还有更多数据
              if (orders.length < pageSize || allOrders.length >= response.data.total) {
                hasMoreData = false
              } else {
                currentPage++
              }
            } else {
              console.warn(`第${currentPage}页订单数据为空或格式错误`)
              hasMoreData = false
            }
          } catch (error) {
            console.warn(`获取第${currentPage}页订单数据失败:`, error)
            hasMoreData = false
          }
        }

        // 计算统计数据
        const now = new Date()
        const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0, 0)
        const todayEnd = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59, 999)
        const todayOrders = allOrders.filter(orderDetail => {
          const orderTime = orderDetail.order?.orderTime || orderDetail.orderTime
          if (orderTime) {
            const orderDate = this.parseChineseDate(orderTime)
            return orderDate && orderDate >= todayStart && orderDate <= todayEnd
          }
          return false
        }).length

        console.log(`订单统计: 总订单数=${allOrders.length}, 今日订单数=${todayOrders}`)
        console.log(`今日时间范围: ${todayStart.toLocaleString()} 到 ${todayEnd.toLocaleString()}`)

        return {
          totalOrders: allOrders.length,
          todayOrders: todayOrders
        }
      } catch (error) {
        console.warn('获取订单统计失败:', error)
        return { totalOrders: 0, todayOrders: 0 }
      }
    },

    /**
       * 获取食品统计数据
       */
    async getFoodStatistics () {
      try {
        // 获取所有食品数据来计算总数
        const allFoods = await this.fetchAllFoodsForStats()
        return {
          totalFoods: allFoods.length
        }
      } catch (error) {
        console.warn('获取食品统计失败:', error)
        return { totalFoods: 0 }
      }
    },

    /**
       * 获取营收统计数据 - 根据对应订单的价格进行绘制
       */
    async getRevenueStatistics () {
      try {
        // 使用订单管理页面相同的分页接口获取所有订单数据
        let allOrders = []
        let currentPage = 1
        const pageSize = 100 // 使用较大的页面大小减少请求次数
        let hasMoreData = true

        while (hasMoreData) {
          try {
            const response = await this.$http.get(`/orderDetails/current/${currentPage}/size/${pageSize}`)
            if (response && response.code === 200 && response.data && response.data.list) {
              const orders = response.data.list
              allOrders = allOrders.concat(orders)

              // 检查是否还有更多数据
              if (orders.length < pageSize || allOrders.length >= response.data.total) {
                hasMoreData = false
              } else {
                currentPage++
              }
            } else {
              hasMoreData = false
            }
          } catch (error) {
            console.warn(`获取第${currentPage}页订单数据失败:`, error)
            hasMoreData = false
          }
        }

        // 计算总营业额
        const totalRevenue = allOrders.reduce((sum, orderDetail) => {
          // 从订单详情中获取总价，支持多种字段名
          const price = orderDetail.order?.totalPrice ||
                         orderDetail.totalPrice ||
                         orderDetail.order?.amount ||
                         orderDetail.amount || 0
          return sum + parseFloat(price)
        }, 0)

        console.log(`营收统计: 总营业额=${totalRevenue.toFixed(2)}元`)

        return {
          totalRevenue: totalRevenue.toFixed(2)
        }
      } catch (error) {
        console.warn('获取营收统计失败:', error)
        return { totalRevenue: '0.00' }
      }
    },

    /**
       * 获取所有食品数据用于统计
       */
    async fetchAllFoodsForStats () {
      const allFoods = []
      const categories = [1, 2, 3] // 推荐、最新、热门
      const indices = [1, 2, 3, 4, 5] // 所有子分类

      try {
        for (const cod of categories) {
          for (const index of indices) {
            try {
              const response = await this.$http.get(`/dishes/cod/${cod}/index/${index}`)
              if (response && response.code === 200 && response.data) {
                allFoods.push(...response.data)
              }
            } catch (error) {
              // 忽略单个分类的错误
            }
          }
        }

        // 去重（基于食品ID或名称）
        const uniqueFoods = allFoods.filter((food, index, self) =>
          index === self.findIndex(f => f.id === food.id || f.dishesName === food.dishesName)
        )

        return uniqueFoods
      } catch (error) {
        console.error('获取食品数据失败:', error)
        return []
      }
    },

    /**
       * 获取食品销量数据
       */
    async fetchFoodSalesData (timeRange) {
      const allFoods = []

      try {
        // 根据时间范围决定获取的数据范围
        const categories = timeRange === 'week'
          ? [1, 2]
          : timeRange === 'month' ? [1, 2, 3] : [1, 2, 3]
        const indices = timeRange === 'week'
          ? [1, 2]
          : timeRange === 'month' ? [1, 2, 3, 4, 5] : [1, 2, 3, 4, 5]

        // 获取所有分类的食品数据
        for (const cod of categories) {
          for (const index of indices) {
            try {
              const response = await this.$http.get(`/dishes/cod/${cod}/index/${index}`)
              if (response && response.code === 200 && response.data) {
                allFoods.push(...response.data)
              }
            } catch (error) {
            }
          }
        }

        return allFoods
      } catch (error) {
        return []
      }
    },

    /**
      * 加载默认数据
      */
    loadDefaultData () {
      const defaultData = this.defaultSalesData[this.timeRange]
      this.chartData = {
        categories: defaultData.categories,
        sales: defaultData.sales
      }
    },

    /**
     * 更新图表
     */
    updateChart () {
      if (!this.chart || !this.chartData.categories.length) {
        return
      }

      const option = {
        title: {
          text: `${this.getTimeRangeText()}食品销量排行榜`,
          left: 'center',
          textStyle: {
            fontSize: 16,
            fontWeight: 'bold',
            color: '#333'
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: (params) => {
            const data = params[0]
            return `<div style="padding: 8px;">
                       <div style="font-weight: bold; margin-bottom: 4px;">${data.name}</div>
                       <div>销量: <span style="color: #409eff; font-weight: bold;">${data.value}</span> 份</div>
                     </div>`
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: this.chartData.categories,
          axisLabel: {
            rotate: 45,
            fontSize: 12,
            interval: 0
          }
        },
        yAxis: {
          type: 'value',
          name: '销量(份)',
          axisLabel: {
            formatter: '{value}'
          }
        },
        series: [{
          name: '销量',
          type: 'bar',
          data: this.chartData.sales,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#83bff6' },
              { offset: 0.5, color: '#188df0' },
              { offset: 1, color: '#188df0' }
            ])
          },
          emphasis: {
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#2378f7' },
                { offset: 0.7, color: '#2378f7' },
                { offset: 1, color: '#83bff6' }
              ])
            }
          },
          barWidth: '60%',
          animationDuration: 1000,
          animationEasing: 'cubicOut'
        }]
      }

      this.chart.setOption(option, true)
    },

    /**
     * 切换时间范围
     */
    async changeTimeRange (range) {
      if (this.timeRange === range) return

      this.timeRange = range
      this.loading = true

      try {
        await this.loadSalesData(range)
        this.updateChart()
      } catch (error) {
        this.$message.error('数据加载失败')
      } finally {
        this.loading = false
      }
    },

    /**
      * 获取时间范围文本
      */
    getTimeRangeText () {
      const timeRangeMap = {
        week: '本周',
        month: '本月',
        year: '本年'
      }
      return timeRangeMap[this.timeRange] || ''
    },

    /**
      * 刷新数据
      */
    async refreshData () {
      await this.loadDashboardData()
      this.updateChart()
      this.$message.success('食品销量数据刷新成功')
    }
  },
  beforeDestroy () {
    // 清理图表实例
    if (this.chart) {
      this.chart.dispose()
      this.chart = null
    }
    // 移除事件监听器
    window.removeEventListener('resize', this.handleResize)
  }
}
</script>

<style scoped>
.dashboard {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: calc(100vh - 60px);
}

.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.stat-item {
  padding: 20px;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.chart-card {
  min-height: 500px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.chart-controls {
  display: flex;
  align-items: center;
}

.chart {
  width: 100%;
  height: 400px;
}

@media (max-width: 768px) {
  .dashboard {
    padding: 10px;
  }

  .chart-header {
    flex-direction: column;
    gap: 10px;
  }

  .chart {
    height: 300px;
  }
}
</style>
